import {
	toolRegisterAll,
	userPersonAll,
	equipmentAll,
	cycleSettingAll,
	equipmentInspectionPlanAdd,
	equipmentInspectionPlanDel,
	equipmentInspectionPlanPage,
	equipmentInspectionPlanUpdate
} from '@/api/device/creatPlan';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';

interface toolRecord {
	name: string;
	equipmentInspectionType: string;
	type: string;
	teamLeaderId: string | number;
	cycleSettingId: string | number;
	equipmentList: (string | number)[];
	duration: number;
	activate: boolean;
	inspectionItemJson: { content: string }[];
	description: string;

	// 假设 columns 中的数据结构如下
	[key: string]: any;
}

interface equipmentInspectionPlanPageResult {
	records: toolRecord[];
	total: number;
	size: number;
	current: number;
	optimizeCountSql: boolean;
	searchCount: boolean;
	pageSize: number;
}

interface ApiResponse<T> {
	code: number;
	message: string;
	data: T;
}

interface PaginationParams {
	current: number;
	pageSize: number;
}

interface FormData {
	name: string;
	equipmentInspectionType: string;
	type: string;
	teamLeaderId: string | number;
	cycleSettingId: string | number;
	equipmentList: (string | number)[];
	duration: number;
	activate: boolean;
	inspectionItemJson: { content: string }[];
	description: string;

	// 假设 columns 中的数据结构如下
	[key: string]: any;
}

export function useToolData() {
	const searchParam = ref({});
	const isLoading = ref(true);
	const searchFields = ref([
		{
			name: 'name',
			label: '计划名称',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		}

	]);
	const InspectionType = ref([
		{
			label: '保养任务',
			value: 1
		},
		{
			label: '点检任务',
			value: 2
		}, {
			label: '巡检任务',
			value: 3
		}

	]);
	const types = ref([
		{
			label: '设备',
			value: 1
		},
		{
			label: '工装',
			value: 2
		}

	]);
	const pageTotal = ref(0);
	const paginatedData = ref<toolRecord[]>([]);
	const paginationParams = ref<PaginationParams>({ current: 1, pageSize: 10 });
	const restForem = ref({
		name: '',
		equipmentInspectionType: '',
		type: '',
		teamLeaderId: '',
		cycleSettingId: '',
		equipmentList: [],
		duration: 0,
		activate: true,
		inspectionItemJson: [{ content: '' }], // 初始化至少一个空项
		description: ''
	});
	const formData = ref<FormData>({
		...restForem.value
	});

	const ruleFormRef = ref<FormInstance>(); // 表单实例引用

	const rules = ref({
		name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
		equipmentInspectionType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
		type: [{ required: true, message: '请选择对象类型', trigger: 'change' }],
		teamLeaderId: [{ required: true, message: '请选择执行人', trigger: 'change' }],
		cycleSettingId: [{ required: true, message: '请选择周期', trigger: 'change' }],
		equipmentList: [{ required: true, message: '请选择设备', trigger: 'change' }],
		duration: [{ required: true, validator: (rule, value) => value > 0, message: '预计耗时必须大于0', trigger: 'change' }],
		activate: [{ required: true, message: '是否启用必填', trigger: 'change' }],
		organizationId: [{ required: true, message: '请选择车间/产线', trigger: 'change' }],
		inspectionItemJson: [{
			required: true,
			validator: (rule, value) => value.length > 0,
			message: '至少添加一项点巡检内容',
			trigger: 'change'
		}],
		description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
	});
	const cycleSetData = ref([]);
	const equipmentData = ref([]);
	const userPersonData = ref([]);
	const toolRegisterData = ref([]);
	const moldType = ref();
	const fetchPageData = async (params: any) => {
		isLoading.value = true;
		try {
			const response = (await equipmentInspectionPlanPage({
				type: params.type || moldType.value,
				...params,
				current: paginationParams.value.current,
				pageSize: paginationParams.value.pageSize


			})) as unknown as ApiResponse<equipmentInspectionPlanPageResult>;

			if (response.code === 200) {
				const { records, total } = response.data;
				paginatedData.value = records.map((item) => {
					return {
						...item.extension,
						...item
					};
				});
				pageTotal.value = total;
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('数据获取失败');
		} finally {
			isLoading.value = false; // 数据加载完成后设置为 false
		}
	};

	onMounted(() => {

		fetchAll();
	});
	const fetchAll = () => {
		cycleSettingAll({ type: 2 }).then(res => {
			cycleSetData.value = res.data;
		});
		equipmentAll({}).then(res => {
			equipmentData.value = res.data;
		});
		userPersonAll({}).then(res => {
			userPersonData.value = res.data;
		});
		toolRegisterAll({}).then(res => {
			toolRegisterData.value = res.data;
		});
	};
	const handleSearch = () => {
		fetchPageData(searchParam.value);
	};

	const handleSizeChange = (val: number) => {
		paginationParams.value.pageSize = val;
		fetchPageData(searchParam.value);
	};

	const handleCurrentChange = (val: number) => {
		paginationParams.value.current = val;
		fetchPageData(searchParam.value);
	};

	const addTool = async (data: Partial<toolRecord>, callback: () => void) => {

		const params = {
			...data,
			equipmentList: data.equipmentList.join(','),
			inspectionItemJson: JSON.stringify(data.inspectionItemJson),
			code: data.name

		};

		if (ruleFormRef.value) {
			await ruleFormRef.value.validate(async (valid) => {
				if (valid) {
					const url = data?.id ? equipmentInspectionPlanUpdate : equipmentInspectionPlanAdd;
					const response = (await url(params)) as unknown as ApiResponse<void>;
					if (response.code === 200) {
						if (data?.id) {
							ElMessage.success('更新成功');
						} else {
							ElMessage.success('添加成功');
						}
						fetchPageData(searchParam.value);
						callback();
					} else {
						ElMessage.error(response.message);
					}
				}
			});
		}
	};

	const deleteTool = async (id: string) => {
		try {
			const response = (await equipmentInspectionPlanDel({ ids: [id] })) as unknown as ApiResponse<void>;
			if (response.code === 200) {
				ElMessage.success('删除成功');
				fetchPageData(searchParam.value);
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('删除失败');
		}
	};

	return {
		searchParam,
		pageTotal,
		paginatedData,
		searchFields,
		isLoading,
		handleSearch,
		handleSizeChange,
		handleCurrentChange,
		addTool,
		deleteTool,
		fetchPageData,
		moldType,
		paginationParams,
		ruleFormRef,
		rules,
		formData,
		types,
		InspectionType,
		cycleSetData,
		equipmentData,
		restForem,
		userPersonData,
		toolRegisterData
	};
}
